package com.aidl.demo.utils;

import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.util.Log;

import java.lang.reflect.Method;

/**
 * Created by Administrator on 2018/7/12 0012.
 */

public class wifiHotUtil {
    public static String SSID = "WIFI-FREE";
    private WifiManager wifiManager = null;
    private Context context;

    public wifiHotUtil(WifiManager wifiManager, Context context) {
        this.wifiManager = wifiManager;
        this.context = context;
    }

    /**
     * 开始启动WiFi热点
     * @param wifi_password
     */
    public void startWifiAp(String wifi_password){
        if (wifiManager.isWifiEnabled()){
            wifiManager.setWifiEnabled(false);
        }else {
            openWifiAp(wifi_password);
        }
    }

    /**
     * 打开WiFi热点
     * @param wifi_password
     */
    private void openWifiAp(String wifi_password) {
        WifiConfiguration configuration = new WifiConfiguration();
        configuration.allowedKeyManagement.set(4);
        configuration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
        configuration.preSharedKey = wifi_password;
        configuration.SSID = SSID;

        try {
            Method method = wifiManager.getClass().getMethod("setWifiApEnabled",WifiConfiguration.class,boolean.class);
            method.invoke(wifiManager,configuration,true);
            Log.d("WifiHotUtil", "WIFI 热点开启成功");
        } catch (Exception e) {
            e.printStackTrace();
            Log.d("WifiHotUtil", "WIFI 热点开启失败");
        }
    }

    /**
     * 判断WIFI热点是否打开
     * @return
     */
    public boolean isWifiApEnable(){
        try {
            Method method = wifiManager.getClass().getMethod("isWifiApEnabled");
            method.setAccessible(true);
            return (boolean) method.invoke(wifiManager);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 关闭WiFi热点
     */
    public void closeWifiAp(){
        if (isWifiApEnable()){
            try {
                Method method1 = wifiManager.getClass().getMethod("getWifiApConfiguration");
                method1.setAccessible(true);
                WifiConfiguration wifiConfiguration = (WifiConfiguration) method1.invoke(wifiManager);
                Method method2 = wifiManager.getClass().getMethod("setWifiApEnabled",WifiConfiguration.class,boolean.class);
                method2.invoke(wifiManager,wifiConfiguration,false);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
